package com.jeecms.wicool.action.activies;

import static com.jeecms.common.page.SimplePage.cpn;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.upload.FileRepository;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.activities.SpecialInfo;
import com.jeecms.wicool.entity.car.CarAdviser;
import com.jeecms.wicool.entity.cms.CmsInfo;
import com.jeecms.wicool.entity.cms.CmsSpecialInfo;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.manager.activities.SpecialInfoMng;
import com.jeecms.wicool.manager.cms.CmsInfoMng;
import com.jeecms.wicool.manager.cms.CmsSpecialInfoMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.util.ConstantUtil;
import com.jeecms.wicool.util.HttpRequestUtil;

/**
 * 组织活动
 * @author hujie
 *
 */
@Controller
public class SpecialInfoAct {
	private static final Logger log = LoggerFactory.getLogger(SpecialInfoAct.class);
	
	@Autowired
	private SpecialInfoMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	  @Autowired
	    private CmsInfoMng cmsInfoMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private FileRepository fileRepository;
	
	@RequestMapping("/specialInfo/v_list.do") 
	public String list(String title,Date publishDate,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(title,publishDate,cpn(pageNo),
				CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("title", title);
		model.addAttribute("publishDate", publishDate);
		return "specialInfo/list_specialInfo";
	}
	
	@RequestMapping("/specialInfo/v_edit.do")
	public String edit(Integer id,String title,Date publishDate, HttpServletRequest request, ModelMap model) {
		WebErrors errors = WebErrors.create(request);
		SpecialInfo SpecialInfo = manager.findById(id);
		if (errors.ifNotExist(SpecialInfo, SpecialInfo.class, id)) {
			return errors.showErrorPage(model);
		}
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("specialInfo", SpecialInfo);
		model.addAttribute("publishTime",format.format(SpecialInfo.getPublishTime()).toString());
		model.addAttribute("q_publishTime", format.format(SpecialInfo.getPublishTime()));
		model.addAttribute("q_title", title);
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "specialInfo/edit_specialInfo";
	}
	@RequestMapping("/specialInfo/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = WebErrors.create(request);
		SpecialInfo SpecialInfo = manager.findById(id);
		if (errors.ifNotExist(SpecialInfo, SpecialInfo.class, id)) {
			return errors.showErrorPage(model);
		}
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("specialInfo", SpecialInfo);
		model.addAttribute("publishTime",format.format(SpecialInfo.getPublishTime()).toString());
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "specialInfo/view_specialInfo";
	}
	@RequestMapping("/specialInfo/o_save.do")
	public String save(SpecialInfo bean,Integer shopId,HttpServletRequest request, ModelMap model) {
		bean.setStatus("0");
		bean.setUpdateTime(new Date());
		CmsUser user = CmsUtils.getUser(request);
		bean.setPublisher(user.getUsername());
		bean.setPublisherId(user.getId().toString());
		bean.setShop(shopMng.findById(shopId));
		SpecialInfo info =manager.save(bean);
//		String specialQRURL = generateQR(info.getSid(), request);
//		if (StringUtils.isNotEmpty(specialQRURL)) {
//			info.setWeixinPicURL(specialQRURL);
//			manager.update(info);
//			log.info("优惠活动二维码生成成功", info.getSid());
//		}else {
//			log.info("优惠活动二维码生成失败", info.getSid());
//		}
		return "redirect:v_list.do";
	}
	@RequestMapping("/specialInfo/o_update.do")
	public String update(SpecialInfo bean,Integer shopId,String q_title,Date q_publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		bean.setUpdateTime(new Date());
		bean.setShop(shopMng.findById(shopId));
		manager.update(bean);
		return list(q_title, q_publishDate, pageNo, request, model);
	}
	
	@RequestMapping("/specialInfo/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		model.addAttribute("publisherName", CmsUtils.getUser(request).getUsername());
		Date nowTime = new Date();
		DateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("publishTime", simpleFormat.format(nowTime));
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "specialInfo/add_specialInfo";
	}
	

	@RequestMapping("/specialInfo/o_delete.do")
	public String delete(Integer[] ids, String title,Date publishDate,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ArrayList<SpecialInfo> SpecialInfo= manager.deleteByIds(ids);
		return list(title,publishDate,pageNo, request, model);
	}
	
	@RequestMapping("/specialInfo/V_publish.do")
	public String pulishView(Integer id,String title,Date publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		SpecialInfo entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, SpecialInfo.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setPublishTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setStatus("1");
		manager.update(entity);
		//把 投票页面链接同步到cms_SpecialInfo表中
				//TODO
		        CmsInfo  ci=new CmsInfo();
				ci.setTitle(entity.getTitle());
				ci.setCmsPath(request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/specialInfo.jspx?specialInfoId="+entity.getSid());
				ci.setOrderNum(entity.getSid());
				ci.setPublisher(CmsUtils.getUser(request));
				ci.setTitleImage(entity.getTitlePicURL());
				ci.setContentId(entity.getSid());
				ci.setIsIndex(Short.valueOf("1"));;
				ci.setStatus(Short.parseShort("-1"));
				ci.setIndexType(1);
				cmsInfoMng.save(ci, entity.getShop().getId());
		
		return list(null, null, pageNo, request, model);
	}
	@RequestMapping("/specialInfo/V_qxpublish.do")
	public String qxpulishView(Integer id,String title,Date publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		SpecialInfo entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, SpecialInfo.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setStatus("0");
		manager.update(entity);
		
		//把 投票页面链接从cms_SpecialInfo表中删除
				//TODO
		CmsInfo ci=cmsInfoMng.findByContentId(entity.getSid());
				if(ci!=null){
					cmsInfoMng.deleteById(ci.getId());
				}
		return list(null, null, pageNo, request, model);
	}
	/**
	 * 发布活动方法 ---------作废
	 * @param id
	 * @param title
	 * @param publishDate
	 * @param logoUrl
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/specialInfo/o_updateStatus.do")
	public String updateStatus(Integer id,String title,Date publishDate,String logoUrl,Integer pageNo,HttpServletRequest request,ModelMap model) {
		SpecialInfo entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, SpecialInfo.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setStatus("1");
		entity.setPublishTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setTitlePicURL(logoUrl);
		manager.update(entity);
		
//		CmsInfo cmsInfo = new CmsInfo();
//		cmsInfo.setTitle(entity.getTitle());
//		cmsInfo.setPublisher(CmsUtils.getUser(request));
//		cmsInfo.setTitleImage(logoUrl);
//		cmsInfo.setContentId(entity.getSid());
		return list(title, publishDate, pageNo, request, model);
	}
	
	@RequestMapping("/specialInfo/o_createSpecialQR.do")
	public String createRQ(Integer id,String title,Date publishDate,String logoUrl,Integer pageNo,HttpServletRequest request,ModelMap model) {
		SpecialInfo entity = manager.findById(id);
		String QRStr = generateQR(entity.getSid(),request);
		if (StringUtils.isNotEmpty(QRStr)) {
			entity.setWeixinPicURL(QRStr);
			manager.update(entity);
			log.info("优惠活动二维码生成成功", entity.getSid());
		}else {
			log.info("优惠活动二维码生成失败", entity.getSid());
		}
		return list(title, publishDate, pageNo, request, model);
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		SpecialInfo entity = manager.findById(id);
		if (errors.ifNotExist(entity, SpecialInfo.class, id)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 调用微信生成接口
	 * @param id
	 * @param request
	 * @return
	 */
	private String generateQR(Integer id,HttpServletRequest request){
		String qRURLStr = ConstantUtil.SPECIALINFOQR+"yhhd_"+id+"&code="+id; 
		String QRstr = HttpRequestUtil.HttpRequest(qRURLStr);
		String QRURL = StringUtils.EMPTY;
		if (StringUtils.isNotEmpty(QRstr)) {
			//解析返回的字符串
			JSONObject ct;
			try {
				ct = new JSONObject(QRstr);
				QRURL = ct.getString("url") == null ? StringUtils.EMPTY : ct.getString("url").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				log.info("微信接口调用失败", id);
			}
			
			if (StringUtils.isNotEmpty(QRURL)) {
				//生成微信二维图
				String qRpathString = fileRepository.CreateQR("QRimg","SPECIALINFOQR_"+id, "png", QRURL);
				return StringUtils.isNotEmpty(qRpathString)?request.getContextPath()+"/"+qRpathString:StringUtils.EMPTY;
			}else {
				return StringUtils.EMPTY;
			}
		}else {
			return StringUtils.EMPTY;
		}
	}
	
}
